const mongoose = require('mongoose');
const Article = mongoose.model('Article');

function getErrorMessage(err) {
    if(err.errors) {
        for(let errName of err.errors) {
            if(err.errors[errName].message) return err.errors[errName].message;
        }
    }else{
        return 'Unkonwn server error';
    }
}

exports.write = function (req, res) {
    const article = new Article(req.body);
    article.creator = req.user._id;

    article.save((err) => {
        if(err) {
            return res.status(400).send({
                message: getErrorMessage(err)
            });
        }else{
            res.status(200).json(article);
        }
    })
};

exports.writeComments = function (req, res) {
    const article = req.article;
    Article.findByIdAndUpdate(article._id, {'$addToSet':
        { 'comments':
           {'content': req.body.content,
            'publisher': req.user._id}
        }
    }, {new: true}, function (err, article) {
        if(err) {
            return res.status(400).send({
                message: getErrorMessage(err)
            })
        }else{
            res.status(200).json(article);
        }
    })
};

exports.cancelComments = function (req, res) {
    const article = req.article;
    article.update({'$pull': {'comments': {'_id': mongoose.Types.ObjectId(req.params.commentId)
    }}}, (err)=> {
        if(err) {
            return res.status(200).send({
                message: getErrorMessage(err)
        });
        }else{
            res.status(200).send({message: 'success!'});
        }
    })
};

exports.list = function (req, res) {
    Article.find().sort('-created').populate(
        'creator', 'username _id followingCount followersCount'
    ).exec((err, articles) => {
        if(err) {
            return res.status(400).send({
                message: getErrorMessage(err)
            });
        }else{
            res.status(200).json(articles)
        }
    })
};

exports.articleByID = function (req, res, next, id) {
    Article.findById(id).populate('creator', 'username _id followingCount')
        .exec((err, article) => {
            if(err) return next(err);
            if(!article) return next(new Error('Failed to load article'));
            req.article = article;
            next();
        })
};

exports.read = function (req, res) {
    res.status(200).json(req.article);
};

exports.update = function (req, res) {
    const article = req.article;

    article.title = req.body.title;
    article.content = req.body.content;

    article.save((err) => {
        if(err) {
            return res.status(400).send({
                message:getErrorMessage(err)
            });
        }else{
            res.status(200).json(article);
        }
    });
};

exports.delete = function (req, res) {
    const article = req.article;

    article.remove((err) => {
        if(err) {
            return res.status(400).send({
                message: getErrorMessage(err)
            });
        }else{
            res.status(200).send({message: 'success!'});
        }
    });
};

exports.hasAuthorization = function (req, res, next) {
    if(req.article.creator._id.toString() !== req.user._id.toString()) {
        return res.status(403).send({message: 'User is not authorized'});
    }
    next();
};

exports.hasConmentsAuthorization = function (req, res, next) {
    var pass = false;
    for(var comment of req.article.comments) {
        if(comment.publisher.toString() == req.user._id.toString()
            || req.article.creator._id.toString() == req.user._id.toString()) pass = true;
    };
    if(!pass) {
        return res.status(403).send({message: 'User is not authorized'});
    }
    next();
}